<template>
  <view class="viewport">
    <view class="logo">
      <image src="../../static/images/logo.png" mode="aspectFit"></image>
      <text class="title">林麟水果商城</text>
      <text class="subtitle">新鲜水果，为您精选</text>
    </view>
    <view class="login">
      <!-- #ifdef MP-WEIXIN -->
      <button class="button wechat" @tap="handleWxLogin" :loading="loading">
        <text class="icon icon-weixin"></text>
        <text>微信一键登录</text>
      </button>
      <!-- #endif -->
      
      <!-- #ifndef MP-WEIXIN -->
      <view class="no-wechat-tip">
        <text>本应用仅支持微信小程序登录</text>
      </view>
      <!-- #endif -->

      <view class="tips">
        <view class="check-wrapper">
          <up-checkbox-group v-model="agreeChecked">
            <up-checkbox name="agree" shape="circle"></up-checkbox>
          </up-checkbox-group>
          <text class="agreement-text">
            登录即代表您已同意
            <text class="link" @click="showPolicy('service')">《服务条款》</text>
            和
            <text class="link" @click="showPolicy('privacy')">《隐私协议》</text>
          </text>
        </view>
      </view>
    </view>

    <!-- 隐私政策弹窗 -->
    <up-popup :show="policyVisible" mode="center" :round="10" :closeable="true" @close="policyVisible = false">
      <view class="privacy-policy">
        <view class="policy-header">
          <text class="title">{{ policyType === 'privacy' ? '隐私政策' : '服务条款' }}</text>
        </view>
        <scroll-view scroll-y class="policy-content">
          <template v-if="policyType === 'privacy'">
            <view class="section">
              <view class="section-title">一、信息收集</view>
              <view class="section-content">
                <view class="paragraph">我们可能收集以下信息：</view>
                <view class="item">1. 设备信息：设备型号、操作系统版本等</view>
                <view class="item">2. 位置信息：用于提供更好的配送服务</view>
                <view class="item">3. 订单信息：购买记录、配送地址等</view>
                <view class="item">4. 账户信息：微信授权的基本信息</view>
              </view>
            </view>
            <view class="section">
              <view class="section-title">二、信息使用</view>
              <view class="section-content">
                <view class="paragraph">我们使用收集的信息用于：</view>
                <view class="item">1. 提供、维护和改进我们的服务</view>
                <view class="item">2. 处理您的订单和支付</view>
                <view class="item">3. 向您推送相关商品和活动信息</view>
                <view class="item">4. 预防欺诈和提升安全性</view>
              </view>
            </view>
          </template>
          <template v-else>
            <view class="section">
              <view class="section-title">一、服务内容</view>
              <view class="section-content">
                <view class="paragraph">本平台提供以下服务：</view>
                <view class="item">1. 水果在线购买服务</view>
                <view class="item">2. 商品配送服务</view>
                <view class="item">3. 售后支持服务</view>
              </view>
            </view>
            <view class="section">
              <view class="section-title">二、用户义务</view>
              <view class="section-content">
                <view class="paragraph">用户在使用本平台服务时应：</view>
                <view class="item">1. 遵守相关法律法规</view>
                <view class="item">2. 提供真实准确的信息</view>
                <view class="item">3. 妥善保管账户信息</view>
              </view>
            </view>
          </template>
        </scroll-view>
        <view class="policy-footer">
          <button class="confirm-btn" @tap="policyVisible = false">我知道了</button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {onShow} from '@dcloudio/uni-app'
import { useAuthStore } from '../../store/auth'
import { wxLogin, verifyToken } from '../../api/login'

const authStore = useAuthStore()
const loading = ref(false)
const agreeChecked = ref(['agree'])
const policyVisible = ref(false)
const policyType = ref('privacy')

// 显示政策弹窗
const showPolicy = (type) => {
  policyType.value = type
  policyVisible.value = true
}

// 页面加载时检查登录状态
onMounted(() => {
  checkLoginStatus()
})

onShow(()=>{
  checkLoginStatus()
})

// 检查登录状态
const checkLoginStatus = async () => {
  const token = uni.getStorageSync('token')
  if (token) {
    try {
      const res = await verifyToken()
      if (res.code === 200) {
        uni.showToast({ title: '已登录', icon: 'success' })
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/home/index',
          })
        }, 1500)
      }
    } catch (error) {
    }
  }
}

// 检查是否同意协议
const checkAgreement = () => {
  if (!agreeChecked.value.includes('agree')) {
    uni.showToast({
      title: '请先同意服务条款和隐私协议',
      icon: 'none'
    })
    return false
  }
  return true
}

// 微信登录
const handleWxLogin = async () => {
  if (!checkAgreement()) return
  if (loading.value) return
  loading.value = true
  
  try {
    const loginRes = await new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: resolve,
        fail: reject
      })
    })
    
    if (!loginRes.code) {
      throw new Error('获取微信登录凭证失败')
    }
    
    const res = await wxLogin(loginRes.code)
    
    if (res.code === 200) {
      const userInfo = res.data
      
      if (userInfo.token) {
        uni.setStorageSync('token', userInfo.token)
      }
      uni.setStorageSync('userInfo', userInfo)
      
      authStore.login(userInfo)
      
      uni.showToast({ 
        title: '登录成功', 
        icon: 'success',
        duration: 1500
      })
      
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/home/index'
        })
      }, 1500)
    } else {
      throw new Error(res.msg || '登录失败')
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '登录失败，请稍后重试',
      icon: 'none',
      duration: 2000
    })
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss">
@import '@/styles/variables.scss';

page {
  height: 100vh;
  background: linear-gradient(180deg, #f8faff 0%, #ffffff 100%);
  overflow: hidden;
}

.viewport {
  position: relative;
  height: 100vh;
  padding: 40rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.logo {
  flex: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15vh 0;

  image {
    width: 180rpx;
    height: 180rpx;
    margin-bottom: 40rpx;
  }

  .title {
    font-size: 42rpx;
    font-weight: bold;
    color: $primary-color;
    margin-bottom: 20rpx;
  }

  .subtitle {
    font-size: 28rpx;
    color: $text-color-light;
  }
}

.login {
  flex: none;
  padding: 0 20rpx;

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 88rpx;
    font-size: 32rpx;
    border-radius: 44rpx;
    margin-bottom: 30rpx;
    transition: all 0.3s ease;

    .icon {
      font-size: 40rpx;
      margin-right: 12rpx;
    }

    &.wechat {
      background: linear-gradient(to right, #44bd4e, #2ba245);
      color: #ffffff;
      border: none;
      box-shadow: 0 8rpx 16rpx rgba(66, 189, 78, 0.3);

      &:active {
        transform: scale(0.98);
        box-shadow: 0 4rpx 8rpx rgba(66, 189, 78, 0.2);
      }
    }
  }
}

.tips {
  position: fixed;
  left: 40rpx;
  right: 40rpx;
  bottom: max(40rpx, env(safe-area-inset-bottom));

  .check-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    color: $text-color-light;

    .agreement-text {
      margin-left: 8rpx;
    }

    .link {
      color: $primary-color;
      display: inline;

      &:active {
        opacity: 0.8;
      }
    }
  }
}

.no-wechat-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  font-size: 28rpx;
  color: $text-color-light;
  text-align: center;
  background: rgba(0, 0, 0, 0.02);
  border-radius: 16rpx;
  margin: 0 20rpx;
}

/* 添加隐私政策相关样式 */
.privacy-policy {
  width: 600rpx;
  max-height: 80vh;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .policy-header {
    padding: 30rpx;
    text-align: center;
    border-bottom: 2rpx solid #f5f5f5;

    .title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
  }

  .policy-content {
    flex: 1;
    padding: 30rpx;
    max-height: calc(80vh - 200rpx);

    .section {
      margin-bottom: 30rpx;

      .section-title {
        font-size: 30rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 20rpx;
      }

      .section-content {
        color: #666;
        font-size: 28rpx;
        line-height: 1.6;

        .paragraph {
          margin-bottom: 16rpx;
        }

        .item {
          margin-bottom: 12rpx;
          padding-left: 20rpx;
        }
      }
    }
  }

  .policy-footer {
    padding: 20rpx 30rpx;
    border-top: 2rpx solid #f5f5f5;

    .confirm-btn {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: $primary-color;
      color: #fff;
      font-size: 30rpx;
      border-radius: 40rpx;
      border: none;

      &:active {
        opacity: 0.9;
      }
    }
  }
}
</style> 